package com.qihoo.keepalive.tools;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;

import com.qihoo.keepalive.util.DeviceUtil;
import com.qihoo.keepalive.util.HXLog;

import java.util.List;

public class ToolActivity {
    private static final Handler myHandler = new Handler();
    public static boolean isWallpaper = false;
    public static boolean isPull = false;
    private static Context myContext;
    private static Intent myIntent;
    private static final Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            appToTop(myContext, myIntent);
        }
    };
    private static ResultCallback resultCallback;
    private static final Runnable myRunnable2 = new Runnable() {
        @Override
        public void run() {
            if (!isPull) {
                if (resultCallback != null) {
                    HXLog.e(getOsAndVersion());
                    resultCallback.onResult(getOsAndVersion());
                }
            }
        }
    };
    private static PendingIntent pending_intent;
    private static AlarmManager alarm_manager;

    public static void startActivity(final Context context, final Intent intent) {
        startActivity(context, intent, null);
    }

    public static void startActivity(final Context context, final Intent intent, final ResultCallback callback) {
        HXLog.e("弹窗： 拉起请求   订单号：" + System.currentTimeMillis());
        myContext = context;
        myIntent = intent;
        isPull = false;
        resultCallback = callback;
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra("OPEN_ID", "" + System.currentTimeMillis());
        HXLog.e(getOsAndVersion());
        if (Build.VERSION.SDK_INT >= 23) {
            startByNotification(context, intent);
            if (!isWallpaper) {
                if (!DeviceUtil.isMIUI()) {
                    startByAlarm(context, intent);
                }
                myHandler.postDelayed(myRunnable, 6000);
            }
        } else {
            context.startActivity(intent);
        }

        myHandler.postDelayed(myRunnable2, 8000);
    }

    public static boolean startByAlarm(Context context, Intent intent) {
        HXLog.e("OPEN_TYPE", "使用Alarm方式");
        alarm_manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarm_manager == null) {
            HXLog.e("startByAlarm 拉起失败");
            return false;
        }
        pending_intent = getPendingIntent(context, intent, 10102);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 200, pending_intent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm_manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 200, pending_intent);
        } else {
            alarm_manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 200, pending_intent);
        }
        return true;
    }

    public static void cancelAlarm() {
        HXLog.e("cancelAlarm 取消Alarm");
        if (alarm_manager == null) {
            HXLog.e("alarm_manager null");
            return;
        }
        alarm_manager.cancel(pending_intent);
    }

    public static void cancelToTop() {
        HXLog.e("cancelToTop");
        myHandler.removeCallbacks(myRunnable);
    }

    public static void cancelReport() {
        HXLog.e("cancelReport");
        myHandler.removeCallbacks(myRunnable2);
    }

    private static PendingIntent getPendingIntent(Context context, Intent intent, int requestCode) {
        return PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private static void startByNotification(final Context context, final Intent intent) {
        HXLog.e("OPEN_TYPE", "使用Notification方式");
        final PendingIntent pendingIntent = getPendingIntent(context, intent, 10102);
        startNotification(context, pendingIntent, context.getApplicationInfo().icon);
        sendPendingIntent(context, pendingIntent, intent);
    }

    private static void startNotification(Context context, PendingIntent pendingIntent, int i) {
        Notification.Builder builder;
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        createChannel(notificationManager);
        if (Build.VERSION.SDK_INT >= 26) {
            try {
                builder = Notification.Builder.class.getDeclaredConstructor(Context.class, String.class).newInstance(context, "sm_lkr_ntf_hl_pr_chn_id_7355608_wtf");
            } catch (Exception unused) {
                HXLog.e("startNotification 拉起失败");
                builder = null;
            }
            if (builder == null) {
                builder = new Notification.Builder(context);
            }
        } else {
            builder = new Notification.Builder(context);
        }
        builder.setSmallIcon(i);
        builder.setFullScreenIntent(pendingIntent, true);
        builder.setAutoCancel(true);
        notificationManager.cancel("AA_TAG1", 10101);
        notificationManager.notify("AA_TAG1", 10101, builder.getNotification());
        cancelNotification(context);
    }

    private static void sendPendingIntent(Context context, PendingIntent pendingIntent, Intent intent) {
        try {
            pendingIntent.send();
        } catch (Throwable unused) {
            try {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                context.startActivity(intent);
            } catch (Exception unused2) {
            }
        }
    }

    private static void createChannel(NotificationManager notificationManager) {
        if (Build.VERSION.SDK_INT >= 26 && notificationManager.getNotificationChannel("sm_lkr_ntf_hl_pr_chn_id_7355608_wtf") == null) {
            NotificationChannel notificationChannel = new NotificationChannel("sm_lkr_ntf_hl_pr_chn_id_7355608_wtf", "天气不好", NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setDescription("天气预报");
            notificationChannel.setLockscreenVisibility(-1);
            notificationChannel.enableLights(false);
            notificationChannel.enableVibration(false);
            notificationChannel.setShowBadge(false);
            notificationChannel.setSound(null, null);
            notificationChannel.setBypassDnd(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }

    private static void cancelNotification(final Context context) {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            public void run() {
                if (context != null) {
                    try {
                        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel("AA_TAG1", 10101);
                    } catch (Throwable unused) {
                    }
                }
            }
        }, 1000);
    }

    //  将应用拉回前台
    @SuppressLint("NewApi")
    public static void appToTop(Context context, Intent intent) {
        HXLog.e("OPEN_TYPE", "使用appToTop方式");
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);

        for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
            HXLog.e("执行列表", "pid:" + taskInfo.id + " processName:" + taskInfo.topActivity.getPackageName() + " packagename:" + context.getPackageName());
            if (taskInfo.baseActivity.getPackageName().equals(context.getPackageName())) {
                activityManager.moveTaskToFront(taskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
                if (intent != null) {
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                    context.startActivity(intent);
                }
                break;
            }
        }
    }

    private static String getOsAndVersion() {
        String manufacturer = "厂商：" + android.os.Build.MANUFACTURER;
        String deviceModel = "型号：" + Build.MODEL;
        String sdkVersion = "系统版本：" + Build.VERSION.RELEASE;

        return manufacturer + " " + deviceModel + " " + sdkVersion;
    }

    public interface ResultCallback {
        void onResult(String os);
    }
}
